<?php

namespace apps\marriage\core\service;

use apps\marriage\core\model\VipCardNo;
use think\Exception;
use vm\com\BaseService;
use vm\org\lock\DisLockFactory;

class VipCardNoService extends BaseService
{
    /**
     * @return VipCardNo
     */
    protected function getModel()
    {
        return new VipCardNo();
    }

    /**
     * @return MemberProfileService
     */
    private function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    /**
     * @return VipCardService
     */
    private function getVipCardService()
    {
        return service('VipCard', SERVICE_NAMESPACE);
    }

    public function onGenerate($vipCardId, $amount)
    {
        for ($k = 1; $k <= $amount; $k++) {
            $no = '';
            while (true) {
                $no = randLimitNumber(1, 9) . rand_string(15, 1);
                if (!parent::info(['no' => $no])) {
                    break;
                }
            }
            $this->create([
                'no' => $no,
                'password' => rand_string(6, 1),
                'vip_card_id' => $vipCardId
            ]);
        }
    }

    public function onActive($userId, $no)
    {
        $lockKey = 'active_vip_card:' . $no;
        $lock = DisLockFactory::instance()->lock($lockKey, 2000);
        if(!$lock) {
            throw new Exception('请重试');
        }
        try {
            $vipCardNo = $this->info(['no' => $no]);
            if(empty($vipCardNo) || $vipCardNo['owner_uid'] > 0) {
                throw new Exception('卡号无效');
            }

            $vipCard = $this->getVipCardService()->getByPk($vipCardNo['vip_card_id']);

            if(time() > $vipCard['end_active_time']) {
                throw new Exception('卡号无效，已超过激活截止日期');
            }
            if(!$this->update([
                'owner_uid' => $userId,
                'active_time' => time()
            ], [
                'no' => $no,
                'owner_uid' => 0
            ])) {
                throw new Exception('激活失败');
            }

            $this->getMemberProfileService()->updateVipLevel($userId, $vipCard['vip_level'], $vipCard['expire_days'] * 3600 * 24);
        } catch (Exception $e) {
            throw $e;
        } finally {
            DisLockFactory::instance()->unlock($lockKey);
        }
    }
}